const Question = require("../model/question.model");
const { Op } = require("sequelize");

const { questionCreateError } = require("../constant/errorType");

class QuestionService {
  // 获取问卷信息
  async getQuestionInfo(query, ctx) {
    const { id } = query;
    const { id: user_id, is_admin } = ctx.state.userInfo;
    const whereOpt = { is_deleted: { [Op.not]: true } };
    !is_admin && Object.assign(whereOpt, { createdId: user_id });
    id && Object.assign(whereOpt, { id });

    const res = await Question.findOne({ where: whereOpt });

    return res.dataValues;
  }

  // 获取问卷列表
  async getQuestionList(query = {}, ctx) {
    const {
      page,
      pageSize,
      is_admin = true,
      keyword,
      isStar,
      isDeleted,
    } = query;
    const config = {
      order: [["updatedAt", "DESC"]],
    };
    page &&
      pageSize &&
      Object.assign(config, {
        offset: (page - 1) * pageSize,
        limit: pageSize - 0,
      });
    const whereOpt = {};
    !is_admin && Object.assign(whereOpt, { createdId: ctx.state.userInfo.id });
    keyword &&
      Object.assign(whereOpt, { title: { [Op.like]: `%${keyword}%` } });
    isStar && Object.assign(whereOpt, { is_star: Boolean(isStar) });

    // 修复 isDeleted 的逻辑：只有当 isDeleted 明确为 true 时才查询已删除的问卷
    // 否则一律不查询已删除的问卷
    if (isDeleted === true || isDeleted === "true") {
      // 只查询已删除的问卷
      Object.assign(whereOpt, { is_deleted: true });
    } else {
      // 不查询已删除的问卷
      Object.assign(whereOpt, { is_deleted: { [Op.not]: true } });
    }

    const res = await Question.findAndCountAll({
      ...config,
      where: whereOpt,
    });

    return res;
  }

  // 创建问卷
  async createQuestion(questionInfo, ctx) {
    try {
      const res = await Question.create(questionInfo);

      return res.dataValues;
    } catch (err) {
      ctx.app.emit("error", { questionCreateError }, ctx);
    }
  }

  // 批量更新问卷
  async updateQuestion(updatedValues, where) {
    return await Question.update(updatedValues, { where });
  }

  // 批量彻底删除问卷
  async deleteQuestionList(where) {
    return await Question.destroy({ where });
  }

  // 获取已发布的问卷信息
  async getPublishedQuestionInfo(id) {
    const whereOpt = {
      id,
      is_deleted: { [Op.not]: true },
      is_published: { [Op.not]: false },
    };

    return await Question.findOne({ where: whereOpt });
  }
}

module.exports = new QuestionService();
